package net.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.concurrent.Callable;

import net.data.AskNamesRequest;
import net.data.FindNameRequest;
import net.data.ResponseResult;
import net.data.SendMessageRequest;
import net.data.SendNameRequest;

public class RequestDispatcherTask implements Callable<ResponseResult>
{
	String destination;
	String query;
	boolean timedOut;
	boolean successful;
	
	public RequestDispatcherTask(FindNameRequest request)
	{
		destination = request.getToAddress();
		timedOut = false;
		query = "findname" +
				"?name=" + request.getName() + 
				"&myip=" + request.getFromAddress() +
				"&ttl=" + request.getTtl();
	}
	
	public RequestDispatcherTask(SendNameRequest request)
	{
		destination = request.getToAddress();
		timedOut = false;
		query = "sendname" +
				"?name=" + request.getName() +
				"&ip=" + request.getAddress() +
				"&ttl=" + request.getTtl();
	}
	
	public RequestDispatcherTask(AskNamesRequest request)
	{
		destination = request.getToAddress();
		timedOut = false;
		query = "asknames" +
				"?ttl=" + request.getTtl(); 
	}
	
	public RequestDispatcherTask(SendMessageRequest request)
	{
		destination = request.getToAddress();
		timedOut = false;
		query = "sendmessage" +
				"?myname=" + request.getName() +
				"&myip=" + request.getFromAddress() +
				"&message=" + request.getMessage() +
				"&ttl=" + request.getTtl();
	}
	
	@Override
	public ResponseResult call() throws Exception
	{
		ResponseResult result = new ResponseResult();
		result.setToAddress(destination);
		result.setQuery(query);
		
		try
		{
			URL url = new URL("http://" + destination + "/chat/" + query);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			
			con.setConnectTimeout(2000);
			con.setReadTimeout(2000);
			con.setDoInput(true);
			con.setRequestMethod("GET");
			con.setRequestProperty("Accept-Charset", "UTF-8. ISO-8859-1");
			con.setRequestProperty("Accept", "text/plain");
			
			BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
			
			String response = "";
			String line;
			while ((line = in.readLine()) != null)
			{
				response += line + '\n';
			}
			
			result.setResponse(response);
			
			successful = true;
			
		}
		catch (MalformedURLException ex)
		{
			successful = false;
		}
		catch(SocketTimeoutException ex)
		{
			successful = false;
			timedOut = true;
		}
		catch (IOException ex)
		{
			successful = false;
		}
		
		return result;
	}

}
